﻿import socket, sys, select, SocketServer, struct, time,base64,zlib
xor = 0x61

def compress(str1):
    return zlib.compress(str1)
def decompress(str1):
    return zlib.decompress(str1)
    
def my_xor(str1):
    l1 = [chr(ord(each)^xor) for each in str1]
    return ''.join(l1)    

class ThreadingTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass
class Decoder(SocketServer.StreamRequestHandler):
    def handle_tcp(self, sock, remote):
        fdset = [sock, remote]
        sock_buf = ''
        while True:
            r, w, e = select.select(fdset, [], [])
            if sock in r:
                if remote.send(my_xor(sock.recv(4096))) <= 0:
                    break
            if remote in r:     
                if sock.send(my_xor(remote.recv(4096))) <= 0:
                    break
                    
    def handle(self):
        try:
            socket1 = self.connection
            data = decompress(socket1.recv(4096))[::-1]
            pos = data.find(',')
            if(pos != -1):           
                remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                remote.connect((data[:pos], int(data[pos+1:])))
                socket1.send('success')
                self.handle_tcp(socket1,remote)
                remote.close()
        except Exception, e:
            print 'socket error',e
def main():
    server = ThreadingTCPServer(('0.0.0.0', 8888), Decoder)
    server.serve_forever()
if __name__ == '__main__':
    main()